package tui

import (
	"fmt"
	"runtime"
	"sync"
	"time"

	"anders-cli/pkg/logger"
)

// PerformanceMonitor 性能监控器
type PerformanceMonitor struct {
	mu              sync.RWMutex
	startTime       time.Time
	messageCount    int
	errorCount      int
	memoryUsage     uint64
	lastCleanupTime time.Time
}

// NewPerformanceMonitor 创建性能监控器
func NewPerformanceMonitor() *PerformanceMonitor {
	return &PerformanceMonitor{
		startTime:       time.Now(),
		lastCleanupTime: time.Now(),
	}
}

// UpdateMetrics 更新性能指标
func (pm *PerformanceMonitor) UpdateMetrics(messageCount, errorCount int) {
	pm.mu.Lock()
	defer pm.mu.Unlock()

	pm.messageCount = messageCount
	pm.errorCount = errorCount
	pm.memoryUsage = pm.getMemoryUsage()

	// 定期清理内存
	if time.Since(pm.lastCleanupTime) > 5*time.Minute {
		pm.cleanupMemory()
		pm.lastCleanupTime = time.Now()
	}
}

// getMemoryUsage 获取内存使用情况
func (pm *PerformanceMonitor) getMemoryUsage() uint64 {
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	return m.Alloc
}

// cleanupMemory 清理内存
func (pm *PerformanceMonitor) cleanupMemory() {
	logger.Info("执行内存清理")
	runtime.GC()

	// 在 Go 1.21+ 中，runtime.ForceGC 和 runtime.ForceFreeOSMemory 已被移除
	// 我们依赖 Go 的自动内存管理
}

// GetStats 获取性能统计
func (pm *PerformanceMonitor) GetStats() PerformanceStats {
	pm.mu.RLock()
	defer pm.mu.RUnlock()

	uptime := time.Since(pm.startTime)

	return PerformanceStats{
		Uptime:       uptime,
		MessageCount: pm.messageCount,
		ErrorCount:   pm.errorCount,
		MemoryUsage:  pm.memoryUsage,
		Goroutines:   runtime.NumGoroutine(),
	}
}

// PerformanceStats 性能统计数据
type PerformanceStats struct {
	Uptime       time.Duration
	MessageCount int
	ErrorCount   int
	MemoryUsage  uint64
	Goroutines   int
}

// FormatMemoryUsage 格式化内存使用量
func (ps PerformanceStats) FormatMemoryUsage() string {
	const unit = 1024
	if ps.MemoryUsage < unit {
		return fmt.Sprintf("%d B", ps.MemoryUsage)
	}
	div, exp := int64(unit), 0
	for n := ps.MemoryUsage / unit; n >= unit; n /= unit {
		div *= unit
		exp++
	}
	return fmt.Sprintf("%.1f %cB", float64(ps.MemoryUsage)/float64(div), "KMGTPE"[exp])
}

// ConnectionPool 连接池管理
type ConnectionPool struct {
	mu          sync.RWMutex
	connections map[string]interface{}
	maxSize     int
}

// NewConnectionPool 创建连接池
func NewConnectionPool(maxSize int) *ConnectionPool {
	return &ConnectionPool{
		connections: make(map[string]interface{}),
		maxSize:     maxSize,
	}
}

// Get 获取连接
func (cp *ConnectionPool) Get(key string) (interface{}, bool) {
	cp.mu.RLock()
	defer cp.mu.RUnlock()

	conn, exists := cp.connections[key]
	return conn, exists
}

// Put 放入连接
func (cp *ConnectionPool) Put(key string, conn interface{}) {
	cp.mu.Lock()
	defer cp.mu.Unlock()

	// 如果达到最大大小，清理最旧的连接
	if len(cp.connections) >= cp.maxSize {
		// 这里可以实现LRU策略
		for k := range cp.connections {
			delete(cp.connections, k)
			break
		}
	}

	cp.connections[key] = conn
}

// Remove 移除连接
func (cp *ConnectionPool) Remove(key string) {
	cp.mu.Lock()
	defer cp.mu.Unlock()

	delete(cp.connections, key)
}

// Size 获取连接池大小
func (cp *ConnectionPool) Size() int {
	cp.mu.RLock()
	defer cp.mu.RUnlock()

	return len(cp.connections)
}

// Cleanup 清理连接池
func (cp *ConnectionPool) Cleanup() {
	cp.mu.Lock()
	defer cp.mu.Unlock()

	cp.connections = make(map[string]interface{})
	logger.Info("连接池已清理")
}

// RequestLimiter 请求限制器
type RequestLimiter struct {
	mu          sync.Mutex
	lastRequest time.Time
	minInterval time.Duration
}

// NewRequestLimiter 创建请求限制器
func NewRequestLimiter(minInterval time.Duration) *RequestLimiter {
	return &RequestLimiter{
		minInterval: minInterval,
	}
}

// Allow 检查是否允许请求
func (rl *RequestLimiter) Allow() bool {
	rl.mu.Lock()
	defer rl.mu.Unlock()

	now := time.Now()
	if now.Sub(rl.lastRequest) < rl.minInterval {
		return false
	}

	rl.lastRequest = now
	return true
}

// GetWaitTime 获取需要等待的时间
func (rl *RequestLimiter) GetWaitTime() time.Duration {
	rl.mu.Lock()
	defer rl.mu.Unlock()

	elapsed := time.Since(rl.lastRequest)
	if elapsed < rl.minInterval {
		return rl.minInterval - elapsed
	}
	return 0
}
